<template>
  <div class="app-container">
    <div class="app-body-center">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <h3>个人信息</h3>
        <el-form-item label="头像" prop="avatar">
          <div style="width: 208px">
            <el-upload
              ref="upload"
              :multiple="false"
              accept=".png, .jpg, .jpeg, .bmp"
              :action="uploadFileUrl"
              :headers="headers"
              :show-file-list="false"
              :before-upload="handleBeforeUpload"
              :on-success="
                (res) => {
                  onSuccess(res, 'avatar');
                }
              "
            >
              <img
                v-if="form.avatar"
                :src="baseUrl + form.avatar"
                style="width: 70px; height: 70px; border-radius: 50%"
              />
              <el-button v-else type="primary">上传</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="用户账号" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入用户账号(电话)"
              :disabled="action != 'add'"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              v-model="form.nickName"
              placeholder="请输入用户昵称"
              maxlength="20"
            />
          </el-form-item>
        </div>

        <div style="display: flex">
          <el-form-item label="姓名" prop="realName">
            <el-input
              v-model="form.realName"
              placeholder="请输入真实姓名"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="充电卡号" prop="cardNo">
            <el-input v-model="form.cardNo" placeholder="请输入充电卡号" maxlength="20" />
          </el-form-item>
        </div>

        <div style="display: flex">
          <el-form-item label="停车点位" prop="areaId">
            <el-select
              v-model="form.areaId"
              filterable
              clearable
              :disabled="action == 'edit'"
              style="width: 100%"
              placeholder="请选择停车点位"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span v-if="item.address" style="color: #ccc"> ({{ item.address }})</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单元号" prop="unitNo">
            <el-input v-model="form.unitNo" placeholder="请输入单元号" maxlength="20" />
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="100"
          />
        </el-form-item>
        <h3 v-if="action != 'edit'">会员信息</h3>
        <div v-if="action != 'edit'" style="display: flex">
          <el-form-item label="会员类型" prop="memberType">
            <el-select
              v-model="form.memberType"
              @change="changeMemberType"
              style="width: 100%"
            >
              <el-option label="充电/停车" :value="1" />
              <el-option label="停车" :value="2" />
              <el-option label="临时用户" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="月租类型" prop="vipType">
            <el-select
              v-model="form.vipType"
              style="width: 100%"
              :disabled="form.memberType == 3"
              @change="changeType"
            >
              <el-option label="月卡" :value="1" />
              <el-option label="季卡" :value="2" />
              <el-option label="年卡" :value="3" />
              <el-option
                v-if="form.memberType == 3"
                :label="form.memberType == 3 ? '非会员' : '会员到期'"
                :value="4"
              />
            </el-select>
          </el-form-item>
        </div>

        <div v-if="action != 'edit' && form.memberType != 3" style="display: flex">
          <el-form-item label="开始时间" prop="vipStartTime">
            <el-date-picker
              v-model="form.vipStartTime"
              type="datetime"
              placeholder="选择日期"
              :picker-options="{
                disabledDate(time) {
                  return form.vipEndTime
                    ? time.getTime() > new Date(form.vipEndTime).getTime()
                    : false;
                },
              }"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="00:00:00"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="vipEndTime">
            <el-date-picker
              v-model="form.vipEndTime"
              type="datetime"
              placeholder="选择日期"
              :picker-options="{
                disabledDate(time) {
                  return form.vipStartTime
                    ? time.getTime() < new Date(form.vipStartTime).getTime()
                    : false;
                },
              }"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="23:59:59"
              style="width: 100%"
            />
          </el-form-item>
        </div>
        <div v-if="action != 'edit' && form.memberType != 3" style="display: flex">
          <el-form-item label="实付金额" prop="vipPrice">
            <el-input
              v-model.number="form.vipPrice"
              placeholder="请输入实付金额"
              type="number"
              maxlength="20"
            >
              <span slot="suffix">元</span>
            </el-input>
          </el-form-item>
          <el-form-item label=""> </el-form-item>
        </div>
        <h3 v-if="action != 'edit'">车辆信息</h3>
        <el-form-item
          v-if="action != 'edit'"
          label="车辆照片"
          prop="vehicle.vehicleImgUrl"
        >
          <el-upload
            ref="upload"
            :multiple="false"
            accept=".png, .jpg, .jpeg, .bmp"
            :action="uploadFileUrl"
            :headers="headers"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="
              (res) => {
                onSuccess(res, 'vehicleImgUrl');
              }
            "
          >
            <img
              v-if="form.vehicle && form.vehicle.vehicleImgUrl"
              :src="baseUrl + form.vehicle.vehicleImgUrl"
              style="width: 100px; height: 70px"
            />
            <el-button v-else type="primary">上传</el-button>
          </el-upload>
        </el-form-item>

        <div style="display: flex" v-if="action != 'edit' && form.vehicle">
          <el-form-item label="车辆品牌" prop="vehicle.vehicleBrand">
            <el-input
              v-model="form.vehicle.vehicleBrand"
              maxlength="10"
              placeholder="请输入车辆品牌"
            />
          </el-form-item>
          <el-form-item label="车牌号" prop="vehicle.vehicleNumber">
            <el-input
              v-model="form.vehicle.vehicleNumber"
              maxlength="10"
              placeholder="请输入车牌号"
            />
          </el-form-item>
        </div>

        <div style="display: flex" v-if="action != 'edit' && form.vehicle">
          <el-form-item label="充电类型" prop="vehicle.vehicleChargeTypeId">
            <el-select v-model="form.vehicle.vehicleChargeTypeId" style="width: 100%">
              <el-option
                v-for="(i, k) in chargeTypeList"
                :key="k"
                :label="i.typeValue"
                :value="i.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="非充电类型" prop="vehicle.vehicleNonChargeTypeId">
            <el-select v-model="form.vehicle.vehicleNonChargeTypeId" style="width: 100%">
              <el-option
                v-for="(i, k) in nonChargeTypeList"
                :key="k"
                :label="i.typeValue"
                :value="i.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getMember, addMember, updateMember } from "@/api/weiriya/member";
import { listChargeType } from "@/api/weiriya/chargeType";
import { listNonChargeType } from "@/api/weiriya/nonChargeType";
import { listArea } from "@/api/weiriya/area";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      areaList: [], // 区域列表
      chargeTypeList: [], // 充电类型列表
      nonChargeTypeList: [], // 非充电类型列表
      memberId: null, // 用户ID
      form: {
        vehicle: {
          vehicleImgUrl: null, // 车辆照片
          vehicleBrand: null, // 车辆品牌
          vehicleNumber: null, // 车牌号
          vehicleChargeTypeId: null, // 充电类型ID
          vehicleNonChargeTypeId: null, // 非充电类型ID
        },
      }, // 表单参数
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户账号(手机号)不能为空", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        cardNo: [{ required: true, message: "充电卡号不能为空", trigger: "blur" }],
        areaId: [{ required: true, message: "停车点位不能为空", trigger: "blur" }],
        unitNo: [{ required: true, message: "单元号不能为空", trigger: "blur" }],
        memberType: [{ required: true, message: "会员类型不能为空", trigger: "blur" }],
        vipType: [{ required: true, message: "月租类型不能为空", trigger: "blur" }],
        vipStartTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
        vipEndTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
        vipPrice: [{ required: true, message: "实付金额不能为空", trigger: "blur" }],
        "vehicle.vehicleImgUrl": [
          { required: true, message: "车辆照片不能为空", trigger: "blur" },
        ],
        "vehicle.vehicleBrand": [
          { required: true, message: "车辆品牌不能为空", trigger: "blur" },
        ],
        "vehicle.vehicleNumber": [
          { required: true, message: "车牌号不能为空", trigger: "blur" },
        ],
        "vehicle.vehicleChargeTypeId": [
          { required: true, message: "充电类型不能为空", trigger: "blur" },
        ],
        "vehicle.vehicleNonChargeTypeId": [
          { required: true, message: "非充电类型不能为空", trigger: "blur" },
        ],
      },
      action: "add", // 操作类型
    };
  },
  mounted() {
    let id = this.$route.query.id;
    this.action = this.$route.query.type || "add";
    this.reset();
    this.getAreaList();
    this.getChargeTypeList();
    this.getNonChargeTypeList();
    if (id) {
      this.memberId = id;
      this.queryForm();
    }
  },
  methods: {
    // 查询停车点位列表
    getAreaList() {
      let data = {
        pageNum: 1,
        pageSize: 1000,
      };
      listArea(data).then((res) => {
        this.areaList = res.rows;
      });
    },
    // 查询充电类型列表
    getChargeTypeList() {
      let data = {
        pageNum: 1,
        pageSize: 1000,
      };
      listChargeType(data).then((res) => {
        this.chargeTypeList = res.rows;
      });
    },
    // 查询非充电类型列表
    getNonChargeTypeList() {
      let data = {
        pageNum: 1,
        pageSize: 1000,
      };
      listNonChargeType(data).then((res) => {
        this.nonChargeTypeList = res.rows;
      });
    },
    // 查询账户信息
    queryForm() {
      getMember(this.memberId).then((res) => {
        this.form = res.data;
      });
    },
    // 上传成功回调
    onSuccess(res, field) {
      if (field == "avatar") {
        this.form[field] = res.fileName;
      } else {
        this.form.vehicle[field] = res.fileName;
      }
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      let typeList = ["png", "jpg", "jpeg", "bmp"];
      const fileName = file.name.split(".");
      const fileExt = fileName[fileName.length - 1];
      if (!typeList.some((i) => i == fileExt)) {
        this.$modal.msgError("文件格式不正确");
        return false;
      }
      return true;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        avatar: null, // 头像
        userName: null, // 用户账号
        nickName: null, // 昵称
        realName: null, // 姓名
        cardNo: null, // 充电卡号
        memberType: null, // 用户类型（1充电+停车会员,2仅停车会员,3临时用户）
        areaId: null, // 停车点位
        unitNo: null, // 单元号
        vipStartTime: null, // 会员开始时间
        vipEndTime: null, // 会员到期时间
        vipPrice: null, // 实付金额
        vipType: null, // 会员类型（1月卡,2季卡,3年卡）
        vehicle: {
          vehicleImgUrl: null, // 车辆照片
          vehicleBrand: null, // 车辆品牌
          vehicleNumber: null, // 车牌号
          vehicleChargeTypeId: null, // 充电类型ID
          vehicleNonChargeTypeId: null, // 非充电类型ID
        },
        remark: null, // 备注
      };
      this.resetForm("form");
    },
    // 会员类型改变
    changeType(val) {
      if (!val) return;
      let date = new Date().getTime();
      if (val == 1) {
        this.form.vipStartTime = this.parseTime(date);
        this.form.vipEndTime = this.parseTime(date + 30 * 24 * 60 * 60 * 1000);
      } else if (val == 2) {
        this.form.vipStartTime = this.parseTime(date);
        this.form.vipEndTime = this.parseTime(date + 90 * 24 * 60 * 60 * 1000);
      } else if (val == 3) {
        this.form.vipStartTime = this.parseTime(date);
        this.form.vipEndTime = this.parseTime(date + 365 * 24 * 60 * 60 * 1000);
      }
    },
    // 会员类型改变
    changeMemberType(val) {
      if (val == 3) {
        this.form.vipType = 4;
        this.form.vipStartTime = null;
        this.form.vipEndTime = null;
        this.form.vipPrice = null;
      } else {
        this.form.vipType = null;
      }
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.id = this.memberId;
          if (this.action == "edit") {
            updateMember(this.form).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.$tab.closeOpenPage("/weiriya/member");
            });
          } else {
            addMember(this.form).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.$tab.closeOpenPage("/weiriya/member");
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-body-center {
  width: 1000px;
  margin: auto;
}
.el-form-item {
  flex: 1;
}
</style>
